package org.opens.javaskill.design;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明:
 *      1. 这是观察者模式的实例.
 */
public class ObserverPattern {

    public static void main(String[] args) {
        Subject subject = new Subject();
        OneObserver oneObserver = new OneObserver("o1", subject);
        OneObserver twoObserver = new OneObserver("o2", subject);

        subject.setState("s1");
        subject.setState("s2");
        subject.setState("s3");
    }

}

class Subject {

    private String state;

    private List<Observer> observerList = new ArrayList<>();

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
        this.notifyAllObserver();
    }

    /**
     * 说明:
     * <pre>
     *     1. 将观察者加入自己要通知的列表中;
     * </pre>
     *
     */
    public void attach(Observer observer) {
        this.observerList.add(observer);
    }

    /**
     * 说明:
     * <pre>
     *     1. 当Subject实例的状态发生变化时, 就通知自己要通知的列表中的所有观察者.
     * </pre>
     *
     */
    public void notifyAllObserver() {
        observerList.forEach(Observer::update);
    }

}

abstract class Observer {

    protected Subject subject;

    protected String name;

    public Observer(String name, Subject subject) {
        this.subject = subject;
        this.name = name;
    }

    public abstract void update();

}

class OneObserver extends Observer {

    public OneObserver(String name, Subject subject) {
        super(name, subject);
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println(this.name + " : 收到subject消息-> " + this.subject.getState());
    }

}

